package epam.car.rent;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import epam.car.rent.exceptions.FileProblemsExceptions;

public class TextFileWriter extends Writer {

	@Override
	public void write(Object context, Object info) {
		BufferedWriter out = null;
		try {
			String[] array = (String[]) info;
			FileWriter fstream = new FileWriter((String) context);
			out = new BufferedWriter(fstream);

			for (int i = 0; i < array.length; i++) {
				out.write((String) array[i]);
			}
		} catch (IOException e) {
			System.out.println("Some IO-error occured during writing file! " + e.getMessage());
			try {
				throw new FileProblemsExceptions(e);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					System.out.println("Something goes weird!");
					try {
						throw new FileProblemsExceptions(e);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		}

	}
	
	@Override
	public ArrayList<String> read(Object context) {
		String line = null;
		ArrayList<String> records = new ArrayList<String>();
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new FileReader((String) context));
			while ((line = bufferedReader.readLine()) != null) {
				records.add(line);
			}
			return records;
		} catch (FileNotFoundException e){
			System.out.println("File not found! " + e.getMessage());
			try {
				throw new FileProblemsExceptions("File not found!", e);
			} catch (Exception e1) {
				e1.printStackTrace();
			} 
		} catch (IOException e) {
			System.out.println("Some IO-error occured during reading file! " + e.getMessage());
			try {
				throw new FileProblemsExceptions(e);
			} catch (FileProblemsExceptions e1) {
				e1.printStackTrace();
			}
		
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}